//用户的增删改查
const db = require('./db')
    //渲染
    //用户列表
const list = () => {
    let sql = `select * from users`
    return new Promise((resolve, reject) => {
        //异步操作，需要使用回调函数
        db.query(sql, (err, result) => {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        })
    })
}

//添加
const add = (req, res) => {
    let sql = `INSERT INTO users(name,price) VALUES (?,?)`
    return new Promise((resolve, reject) => {
        db.query(sql, [req.body.name, req.body.price], (err, result) => {
            if (err) {
                reject(err)
            } else {
                resolve(result)
            }
        })
    })
}

//删除
const del = (req, res) => {
    console.log(req.body);
    let sql = `DELETE FROM users WHERE id=${req.body.id};`
    return new Promise((resolve, reject) => {
        db.query(sql, (err, result) => {
            if (err) {
                reject(err)
            } else {
                resolve(result)
            }
        })
    })
}

//修改
const mod = (req, res) => {
    console.log(req.body);
    let sql = `UPDATE users SET name='${req.body.name}',price=${req.body.price} WHERE id=${req.body.id};`
    return new Promise((resolve, reject) => {
        db.query(sql, (err, result) => {
            if (err) {
                reject(err)
            } else {
                resolve(result)
            }
        })
    })
}
module.exports = {
    list,
    add,
    del,
    mod
}